(function ($) {
    // -------------------------------------------------------
    // Private Variables
    // -------------------------------------------------------
    var _wnd = $(window);
    var _doc = $(document);
    var _body = $('body');
    var _wxwnd = window;
    var _wxdoc = document;
    var dialogs = [];
    var iframes = [];
    var overlays = [];

    // -------------------------------------------------------
    // dialog插件的定义 
    // -------------------------------------------------------
    $.fn.dialog = function (options) {
        return this.each(function () {
            var opts     = $.extend({}, $.fn.dialog.defaults, options),
                $overlay = $(),
                $dialog  = $(),
                $iframe  = $(),
                _zIndex  = 0;

            /*----------------------------------------------------
             DOM Building
             ---------------------------------------------------- */
            // 初始化遮罩蒙板
            CreateOverlay();
            // 创建对话框窗口
            CreateDialogWindow();
            // 设置对话框窗口事件
            SetDialogWindowEvent();
            opts.onLoad($dialog);

            /*----------------------------------------------------
             Private Functions
             ---------------------------------------------------- */
            function CreateOverlay() {
                if (opts.modal) {
                    var serial = overlays.length;
                    var _overlayId = opts.overlayId + '_' + serial;
                    _zIndex = opts.zIndex + serial * 2;
                    $overlay = $('<div id="' + _overlayId + '"/>');
                    $overlay.addClass("dialog__overlay").appendTo('body').show();
                    // 将遮罩放到数组保存
                    overlays.push($overlay);
                }
            }
            function CreateDialogWindow() {
                var html = '';
                if (opts.boxHtml !== '') {
                    html = opts.boxHtml;
                } else {
                    var serial = dialogs.length;
                    var _dialogId = opts.dialogId + '_' + serial;
                    html = '<div id="' + _dialogId + '" class="dialog__box">' +
                            '   <div class="dialog__box_header">' +
                            '       <h2 id="dialog__title"></h2>' +
                            '       <div class="dialog__close_icon" title="关闭"></div>' +
                            '   </div>' +
                            '   <div class="dialog__content">' +
                            '   </div>' +
                            '</div>';
                }
                $dialog = $(html).appendTo($overlay).hide();
                $dialog.css({width: opts.mWidth, height: opts.mHeight});
                $dialog.find("div.dialog__content").css({left: 3, width: opts.mWidth - 6, height: opts.mHeight - 28});
                $dialog.find("#dialog__title").text(opts.mTitle);

                switch (opts.dialog_type) {
                    case 0:
                        if (opts.isIframe === 1) {
                            var _iframeId = opts.iframeId + '_' + serial;
                            $iframe = $('<iframe id="' + _iframeId + '" name="dialog-frame" class="dialog__frame" frameborder="0" vspace="0" marginWidth="0" marginHeight="0" src=""></iframe>');
                            $dialog.find('div.dialog__content').append($iframe);
                            $dialog.find("iframe.dialog__frame").css({width: opts.mWidth - 6, height: opts.mHeight - 28, _height: opts.mHeight - 18})
                                    .attr("src", opts.iframeSrc);
                            iframes.push($iframe);
                        } else {
                            loadPage(opts.mSrc, $('div.dialog__content'));
                        }
                        break;
                    case 1:  // 确认信息窗口
                        var markup = ['<div id="confirmBox">',
                            '<div class="msg__text">' + opts.msgText + '</div>',
                            '<div id="but__strip">',
                            '    <button type="button" tabindex="1" id="dialog__btn_ok" class="act__button dialog__button"><i class="fa-all fa-1x fa-check" style="margin-right:3px; color:green;"></i>确定</button>',
                            '    <button type="button" tabindex="2" id="dialog__btn_cancel" class="act__button"><i class="fa-all fa-1x fa-times" style="margin-right:3px; color:red;"></i>取消</button>',
                            '</div></div>'
                        ].join('');
                        $dialog.find('div.dialog__content').append($(markup));
                        break;
                    case 2:  // 警告信息窗口
                        var markup = ['<div id="alertBox">',
                            '<div class="msg__text">' + opts.msgText + '</div>',
                            '<div id="but__strip">',
                            '    <button type="button" tabindex="1" id="dialog__btn_ok" class="act__button dialog__button"><i class="fa-all fa-1x fa-check" style="margin-right:3px; color:green;"></i>确定</button>',
                            '</div></div>'
                        ].join('');
                        $dialog.find('div.dialog__content').append($(markup));
                        break;
                        // 成功提示 
                    case 3:
                        var markup = ['<div id="successBox">',
                            '<div class="msg__text">' + opts.msgText + '</div>',
                            '<div id="but__strip">',
                            '    <button type="button" tabindex="1" id="dialog__btn_ok" class="act__button dialog__button"><i class="fa-all fa-1x fa-check" style="margin-right:3px; color:green;"></i>确定</button>',
                            '</div></div>'
                        ].join('');
                        $dialog.find('div.dialog__content').append($(markup));
                        break;
                        // 错误提示 
                    case 4:
                        var markup = ['<div id="errorBox">',
                            '<div class="msg__text">' + opts.msgText + '</div>',
                            '<div id="but__strip">',
                            '    <button type="button" tabindex="1" id="dialog__btn_ok" class="act__button dialog__button"><i class="fa-all fa-1x fa-check" style="margin-right:3px; color:green;"></i>确定</button>',
                            '</div></div>'
                        ].join('');
                        $dialog.find('div.dialog__content').append($(markup));
                        break;
                }
                setCenterPosition();
                $dialog.show();
                dialogs.push($dialog);

                $(window).resize(function () {
                    setCenterPosition();
                    //var winX = ($(window).width() - $dialog.width()) / 2 + "px";
                    //var winY = ($(window).height() - $dialog.height()) / 2 + $(window).scrollTop() + "px";
                    //$dialog.css({left: winX, top: winY});
                });
            }
            function SetDialogWindowEvent() {
                $dialog.find(".dialog__close_icon").unbind('click').bind('click', CloseDialogWindow);
                if (opts.dialog_type === 1) {
                    $dialog.find("#dialog__btn_ok").unbind('click').bind('click', ClickOK);
                    $dialog.find("#dialog__btn_cancel").unbind('click').bind('click', ClickCancel);
                }
                if ((opts.dialog_type === 2) || (opts.dialog_type === 3) || (opts.dialog_type === 4)) {
                    $dialog.find("#dialog__btn_ok").unbind('click').bind('click', CloseDialogWindow);
                }
                drag();
            }
            function ClickOK() {
                CloseDialogWindow();
                // 调用回调函数
                if (opts.onOkClick)
                    opts.onOkClick();
            }
            function ClickCancel() {
                CloseDialogWindow();
                // 调用回调函数
                if (opts.onCancelClick)
                    opts.onCancelClick();
            }
            function CloseDialogWindow() {
                // 调用回调函数
                if (opts.onClose)
                    opts.onClose($dialog);

                $dialog.find(".dialog__close_icon").unbind('click');
                if (opts.dialog_type === 0) {
                    if ($iframe) {
                        $iframe.remove();
                        iframes.splice($.inArray($iframe, iframes), 1);
                        $iframe = $();
                    }
                }
                if ($dialog) {
                    $dialog.remove();
                    dialogs.splice($.inArray($dialog, dialogs), 1);
                    $dialog = $();
                }
                if ($overlay) {
                    $overlay.remove();
                    overlays.splice($.inArray($overlay, overlays), 1);
                    $overlay = $();
                }
            }
            // 弹窗拖拽
            function drag() {
                if (opts.draggable) {
                    $dialog.find(".dialog__box_header").mousedown(function (event) {
                        if ($(event.target.closest("div.dialog__close_icon")).length > 0) {
                            return false;
                        }
                        var h = this;
                        var o = _wxdoc;
                        var ox = $dialog.position().left;
                        var oy = $dialog.position().top;
                        var mx = event.clientX;
                        var my = event.clientY;
                        var width = $dialog.width();
                        var height = $dialog.height();   // 还要加上头的高度
                        var bwidth = $overlay.width();
                        var bheight = $overlay.height();
                        $('body').css({cursor: 'move'});

                        var docHeight = $dialog.height() + "px";
                        var docWidth = $dialog.width() + "px";
                        var copyTop = $dialog.offset().top + "px";
                        var copyLeft = $dialog.offset().left + "px";
                        var copy_wnd_style = "position:absolute;top:" + copyTop + ";left:" + copyLeft + ";width:" + docWidth + ";height:" + docHeight + ";background: transparent;z-index:+1;cursor:move;border:1px #000 dotted";
                        var shield_style = "position:absolute;top:0px;left:0px;width:" + docWidth + ";height:" + docHeight + ";z-index:100001;filter:alpha(opacity=0);opacity:0;cursor:move;background:#000;border:1px #000 solid";
                        $("<div id='shield' style=\"" + shield_style + "\"></div>").appendTo();
                        $("<div id='copy_wnd' style=\"" + copy_wnd_style + "\"></div>").appendTo($overlay);

                        $('body').mousemove(function (event) {
                            event.preventDefault();
                            $('body').css({cursor: 'move'});
                            if (_wxwnd.getSelection) {
                                _wxwnd.getSelection().removeAllRanges();
                            } else {
                                _wxdoc.selection.empty();
                            }
                            var left = Math.max(ox + event.clientX - mx - 20, 20 - $dialog.width());
                            var top = Math.max(oy + event.clientY - my, 20 - $dialog.height());
                            //var left = Math.min(left, bwidth-width);
                            //var top = Math.min(top, bheight-height);
                            $("#copy_wnd").css({left: left, top: top});
                        }).mouseup(function () {
                            if (h.releaseCapture) {
                                h.releaseCapture();
                            }
                            var left = $("#copy_wnd").offset().left;
                            var top = $("#copy_wnd").offset().top;
                            $dialog.css({left: left, top: top});
                            $('body').unbind('mousemove');
                            $('body').unbind('mouseup');
                            $('body').css({cursor: 'default'});
                            $("#copy_wnd").remove();
                            $("#shield").remove();
                        });
                    });
                }
            }
            // 将弹窗显示在中间位置
            function setCenterPosition() {
                var pTop = _doc.scrollTop(), pLeft = _doc.scrollLeft();
                pTop += ($overlay.height() - $dialog.height()) / 2;
                if (pTop <= 0)
                    pTop = 0;
                pLeft += ($overlay.width() - $dialog.width()) / 2;
                $dialog.css({top: pTop, left: pLeft});
            }
            // 取得遮照高度
            function bheight() {
                /*
                 if (isIE6) {
                 var scrollHeight = Math.max(
                 _wxdoc.documentElement.scrollHeight,
                 _wxdoc.body.scrollHeight
                 );
                 var offsetHeight = Math.max(
                 _wxdoc.documentElement.offsetHeight,
                 _wxdoc.body.offsetHeight
                 );
                 
                 if (scrollHeight < offsetHeight) {
                 return _wnd.height();
                 } else {
                 return scrollHeight;
                 }
                 } else {*/
                return Math.max(_doc.height(), _wnd.height());
                //return _doc.height();
                //}
            }
            //取得遮照宽度
            function bwidth() {
                /*if (isIE6) {
                 var scrollWidth = Math.max(
                 _wxdoc.documentElement.scrollWidth,
                 _wxdoc.body.scrollWidth
                 );
                 var offsetWidth = Math.max(
                 _wxdoc.documentElement.offsetWidth,
                 _wxdoc.body.offsetWidth
                 );
                 
                 if (scrollWidth < offsetWidth) {
                 return _wnd.width();
                 } else {
                 return scrollWidth;
                 }
                 } else {*/
                return _doc.width();
                // }
            }
            // 装载外部html
            function loadPage(url, $obj) {
                $obj.load(url, function (data) {
                    var startBody = data.indexOf("<body>");
                    var endBody = data.indexOf("</body>");
                    var bodyString = data.substring(startBody + 6, endBody);
                    $obj.html(bodyString);
                });
            }
        });
    };
    // -------------------------------------------------------
    // Default Settings
    // -------------------------------------------------------
    $.fn.dialog.defaults = {
        // behavior
        drag: true,
        showOverlay: true,
        modal: true,
        isSub: false,
        draggable: true,
        dialog_type: 0, // 0-iframe 1-confirm

        overlayId: 'wx-overlay',
        dialogId: 'wx-dialog',
        iframeId: 'wx-dialog-iframe',
        title: '',
        content: '',
        base: "",
        // style
        bgColor: '#000',
        opacity: 0.4,
        filter: 'alpha(opacity=60)',
        zIndex: 999,
        mWidth: 670,
        mHeight: 430,
        mTitle: '编辑',
        mSrc: '',
        isIframe: 0,
        iframeSrc: '',
        boxHtml: '',
        msgText: '',
        // callbacks
        onLoad: $.noop,
        onClose: $.noop,
        onOkClick: $.noop,
        onCancelClick: $.noop
    };
})(jQuery);